var express = require("express");
var router = express.Router();
const moment = require("moment");
const AccountModel = require("../../models/AccountModel");
const checkLoginMioddleWare = require("../../middlewares/authSession");

// 首页
router.get("/", (req, res) => {
  res.redirect("/account");
});

// 账单列表
router.get("/account", checkLoginMioddleWare, async function (req, res, next) {
  AccountModel.find()
    .sort({ time: -1 })
    .exec((err, data) => {
      if (err) {
        res.status(500).send("读取失败~~~");
        return;
      }
      //响应成功的提示
      res.render("list", { accounts: data, moment: moment });
    });
});

// 账单列表创建
router.get("/account/create", checkLoginMioddleWare, function (req, res, next) {
  res.render("create");
});

// 添加账单
router.post("/account", checkLoginMioddleWare, function (req, res, next) {
  AccountModel.create(
    {
      ...req.body,
      // 字符串转对象，对象转时间对象
      time: moment(req.body.time).toDate(),
    },
    (err) => {
      if (err) {
        return res.status(500).send("插入失败");
      }
      res.render("success", { msg: "添加成功哦~~~~", url: "/account" });
    }
  );
});

// 账单删除
router.get("/account/:id", checkLoginMioddleWare, function (req, res, next) {
  // mongodb内部会间将_id赋值给一个隐藏的id字段
  const id = req.params.id;
  AccountModel.deleteOne({ id }, (err) => {
    if (err) {
      return res.status(500).send("删除失败");
    }
    res.render("success", { msg: "删除成功哦~~~~", url: "/account" });
  });
});

module.exports = router;
